<?php

namespace app\admin\controller\fp;

use app\common\controller\Backend;
use app\common\enum\fp\MediaType;
use app\common\enum\fp\PostAuditEnum;
use app\common\enum\fp\PostType;
use app\common\library\Upload;
use app\common\model\fp\Post;
use app\common\model\fp\PostMedia;
use app\logic\fp\PostLogic;
use think\facade\Db;
use think\facade\Event;
use Throwable;

/**
 * 朋友圈-动态审核
 */
class PostAudit extends Backend
{
    /**
     * Audit模型对象
     * @var object
     * @phpstan-var \app\common\model\fp\PostAudit
     */
    protected object $model;

    protected string|array $defaultSortField = ['status'=>'asc'];

    protected array|string $preExcludeFields = [];

    protected string|array $quickSearchField = ['status', 'id'];

    protected array $withJoinTable = ['admin'];

    private PostLogic $logic;

    private \app\common\library\upload\Driver|bool $uploadDriver;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = \app\common\model\fp\PostAudit::initModel();
        $this->logic = new PostLogic();
        $upload = new Upload();
        $conf = get_upload_config();
        $this->uploadDriver = $upload->getDriver($conf['mode'], false);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $where[] = ['post_audit.type', '=', PostType::Normal->value];
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $res->each(function ($item, $key) {
            $temp = json_decode($item['video_cover_url_bak'], true);
            $arr = [];
            foreach ((array)$temp as $k => $v) {
                $arr[] = $this->uploadDriver->url($v);
            }
            $item['video_cover_url_bak'] = $arr;
            $item['video_cover_url'] = $this->uploadDriver->url($item['video_cover_url']);
        });
        $res->visible(['admin' => ['nickname']]);



        $list = $res->items();
        $userIds = array_column($list, 'user_id');
        $postIds = array_column($list, 'post_id');

        if ($userIds) {
            $tables = [];
            foreach ($userIds as $userId) {
                $table = Post::getDbTableName($userId);
                $tables[$table] = $table;
            }

            $post = [];
            foreach ($tables as $table) {
                $postTemp = Db::table($table)->where('id', 'in', $postIds)->field('id,content,title')->select()->toArray();
                $post = array_merge($post, $postTemp);
            }
            $post = array_column($post, null, 'id');
            foreach ($list  as &$item) {
                $item['post'] = $post[$item['post_id']] ?? [];
            }
        }


        $this->success('', [
            'list'   => $list,
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->with(['admin'])->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();

            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }

                $findMedia = PostMedia::initModel($row['user_id'])->where('post_id', $row['post_id'])->find();

                if ($findMedia['media_type'] === MediaType::VIDEO->value && empty($data['video_cover_url'])) {
                    throw new \RuntimeException(__('video_cover_url is required'));
                }
                $data['audit_user_id'] = $this->auth->getAdmin()->id;

                PostMedia::initModel($row['user_id'])->where('post_id', $row['post_id'])->update(['video_cover_url' => $data['video_cover_url']]);

                // 调用业务逻辑层的审核方法
                $result= $this->logic->audit($data);

                //审核通过的才投递事件
                if (PostAuditEnum::from($result['status']) === PostAuditEnum::APPROVED) {
                    Event::trigger('postAudit', $result);
                }
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $upload = new Upload();
        $conf = get_upload_config();
        $driver = $upload->getDriver($conf['mode'], false);
        $row['video_cover_sign_url'] = $row['video_cover_url'] ? $driver->url($row['video_cover_url']) : '';
        $video_cover_url_bak = json_decode($row['video_cover_url_bak'], true);
        if ($video_cover_url_bak) {
            $arr = [];
            foreach ($video_cover_url_bak as $v) {
                $arr[] = [
                    'src' => $v,
                    'url' => $driver->url($v)
                ];
            }
            $row['video_cover_url_bak'] = $arr;
        }

        $row['post'] = PostLogic::getInstance()->adminGetInfo($row['post_id'], $row['user_id']);
        $this->success('', [
            'row' => $row
        ]);
    }
    /**
     * 审核功能
     * 该方法用于处理审核流程，包括参数验证、日志记录和审核状态更新
     */
    public function audit()
    {
        // 实例化验证器以检查参数是否符合规范
        $validate = new \app\admin\validate\fp\PostAudit();
        try {
            // 使用特定场景进行参数验证
            $validate->scene('audit')->check($this->request->param());
        } catch (\think\exception\ValidateException $e) {
            // 验证失败时显示错误信息
            $this->error($e->getMessage());
        }
        // 获取请求参数并添加当前审核用户的ID
        $param = $this->request->param();
        $param['audit_user_id'] = $this->auth->id;
        try {
            // 调用业务逻辑层的审核方法
            $audit= $this->logic->audit($param);

            //审核通过的才投递事件
            if (PostAuditEnum::from($audit['status']) === PostAuditEnum::APPROVED) {
                Event::trigger('postAudit', $audit);
            }
        } catch (\Exception $e) {
            // 记录异常日志并显示审核失败信息
            \think\facade\Log::channel('my')->error($e->getMessage().PHP_EOL.$e->getTraceAsString());
            $this->error(__('audit failed') .', '. $e->getMessage());
        }

        // 审核成功时显示成功信息
        $this->success(__('audit success'));
    }
}